﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Entities.Enums;
using Interview_Prov.Controls;

namespace Interview_Prov.Private.User
{
    public partial class InterviewPage : System.Web.UI.Page
    {
        Business.BusinessLogic bll = new Business.BusinessLogic();
        public Interview SrcInterview { get; set; }
        public bool EditMode { get; set; }
        private int total_counter = 0;

        protected void ControlsReloadBack()
        {
            if (QuestionCount != 0)
            {
                for (int i = 0; i < QuestionCount; i++)
                {
                    questions_ph.Controls.Add(MakeQuestionCtl(i));
                }
                total_counter = QuestionCount;
            }
            //QuestionCount = 0;
        }

        public int QuestionCount
        {
            get
            {
                if (ViewState["QuestionCount"] != null)
                {
                    return (int)ViewState["QuestionCount"];
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                ViewState["QuestionCount"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int interview_id = GetInterviewID();

            if (interview_id == -1)
            {
                Response.Redirect("~/SelectInterview.aspx?ReturnUrl=/Private/User/InterviewPage.aspx?EditMode=1", true);
            }

            SrcInterview = bll.LoadInterview(GetInterviewID());

            if (SrcInterview.ID == -1)
            {
                Response.Redirect("~/Errors/InterviewLoadError.aspx", true);
                return;
            }

            EditMode = false;
            if (Global.UserLevel == "admin" || Global.UserLevel == "moderator")
            {
                if (DetectEditMode())
                {
                    EditMode = true;
                }
            }
            else
            {
                if (SrcInterview.State == InterviewState.Draft || SrcInterview.State == InterviewState.Closed)
                {
                    Response.Redirect("~/Errors/InterviewAccessError.aspx", true);
                }
            }

            this.btn_complete.Visible = !EditMode;
            this.btn_save.Visible = EditMode;
            this.btn_question_add.Visible = EditMode;

            if (IsPostBack)
            {
                ControlsReloadBack();
            }
            else
            {
                for (int i = 0; i < SrcInterview.Questions.Count(); i++)
                {
                    questions_ph.Controls.Add(MakeQuestionCtl(i));
                    QuestionCount++;
                }
            }
        }

        protected Control MakeQuestionCtl(int index)
        {
            index += total_counter;
            var q_ctl = (Question_Ctl)LoadControl("~/Controls/Question_Ctl.ascx");
            q_ctl.DeleteClicked += new EventHandler<QuestionEventArgs>(Question_DeleteClicked);
            q_ctl.QuestionWithoutAnswerDetected += new EventHandler<QuestionEventArgs>(QuestionWithoutAnswerDetected_Event);
            q_ctl.ID = makeID(index);
            q_ctl.RelativeQuestionNumber = index;
            q_ctl.EditMode = this.EditMode;
            q_ctl.SrcQuestion = SrcInterview.Questions[index];

            return q_ctl;
        }

        private List<int> FailedQuestions = new List<int>();
        void QuestionWithoutAnswerDetected_Event(object sender, QuestionEventArgs e)
        {
            FailedQuestions.Add(e.Index);
        }

        protected void Question_DeleteClicked(object sender, QuestionEventArgs e)
        {
            SrcInterview.Questions.RemoveAt(e.Index);
            QuestionCount--;
            questions_ph.Controls.Remove(questions_ph.FindControl(makeID(e.Index)));
            SrcInterview.ChgState = Entities.Enums.EntityState.Changed;
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            if (IsPostBack)
            {
                if (SrcInterview.ChgState != Entities.Enums.EntityState.Changed)
                {
                    foreach (var quest in SrcInterview.Questions)
                    {
                        if (quest.ChgState != Entities.Enums.EntityState.Unchanged)
                            SrcInterview.ChgState = Entities.Enums.EntityState.Changed;
                    }
                }

                if (EditMode)
                {
                    if (SrcInterview.ChgState == Entities.Enums.EntityState.Changed)
                    {
                        SrcInterview.State = Entities.Enums.InterviewState.Draft;
                        bll.ModifyInterview(SrcInterview);
                    }
                }
                else
                {
                    List<QuestionRunResultData> qrd_list = new List<QuestionRunResultData>();
                    foreach (var qctl in questions_ph.Controls)
                    {
                        Question_Ctl question = (Question_Ctl)qctl;
                        if (!FailedQuestions.Contains(question.RelativeQuestionNumber))
                        {
                            qrd_list.Add(question.Result);
                        }
                    }
                    InterviewRunResultData irrd = new InterviewRunResultData(SrcInterview.ID, Global.UserID, qrd_list);
                    bll.SaveInterviewRunResult(irrd);
                    Response.Redirect(string.Format("~/CommonStats.aspx?InterviewID={0}",SrcInterview.ID),true);
                }
            }
            base.OnPreRenderComplete(e);
        }

        private string makeID(int index)
        {
            return string.Format("Question_Ctl{0}", index);
        }

        protected bool DetectEditMode()
        {
            int reqmode = 0;
            if (Request.Params["EditMode"] != null)
            {
                int.TryParse(Request.Params["EditMode"], out reqmode);
            }
            return (reqmode == 1);
        }

        protected int GetInterviewID()
        {
            int iid = -1;
            if (Request.Params["InterviewID"] != null)
            {
                int.TryParse(Request.Params["InterviewID"], out iid);
            }
            return iid;
        }

        protected void btn_question_add_Click(object sender, EventArgs e)
        {
            SrcInterview.AddQuestion(new Question("NewQuestion", new List<string>(), QuestionType.MultipleChoice));
            QuestionCount++;
            var qctl = MakeQuestionCtl(0);
            questions_ph.Controls.Add(qctl);
            SrcInterview.ChgState = Entities.Enums.EntityState.Changed;
        }
    }
}